import type { SymbolLibrary, FormulaSymbol, SymbolCategory } from '../types';

// 符号库定义
export const symbolLibrary: SymbolLibrary = {
  basic: [
    { label: '+', latex: '+', category: 'basic', description: '加' },
    { label: '-', latex: '-', category: 'basic', description: '减' },
    { label: '×', latex: '\\times', category: 'basic', description: '乘' },
    { label: '÷', latex: '\\div', category: 'basic', description: '除' },
    { label: '=', latex: '=', category: 'basic', description: '等于' },
    { label: '≠', latex: '\\neq', category: 'basic', description: '不等于' },
    { label: '<', latex: '<', category: 'basic', description: '小于' },
    { label: '>', latex: '>', category: 'basic', description: '大于' },
    { label: '≤', latex: '\\leq', category: 'basic', description: '小于等于' },
    { label: '≥', latex: '\\geq', category: 'basic', description: '大于等于' },
  ],
  functions: [
    { label: 'sin', latex: '\\sin', category: 'functions', description: '正弦' },
    { label: 'cos', latex: '\\cos', category: 'functions', description: '余弦' },
    { label: 'tan', latex: '\\tan', category: 'functions', description: '正切' },
    { label: 'log', latex: '\\log', category: 'functions', description: '对数' },
    { label: 'ln', latex: '\\ln', category: 'functions', description: '自然对数' },
    { label: 'sqrt', latex: '\\sqrt{}', category: 'functions', description: '平方根' },
    { label: 'nthroot', latex: '\\sqrt[n]{}', category: 'functions', description: 'n次方根' },
    { label: 'exp', latex: '\\exp', category: 'functions', description: '指数函数' },
  ],
  matrix: [
    { label: '矩阵(2×2)', latex: '\\begin{bmatrix} a & b \\ c & d \\ \end{bmatrix}', category: 'matrix', description: '2x2矩阵' },
    { label: '矩阵(3×3)', latex: '\\begin{bmatrix} a & b & c \\ d & e & f \\ g & h & i \\ \end{bmatrix}', category: 'matrix', description: '3x3矩阵' },
    { label: '行列式(2×2)', latex: '\\begin{vmatrix} a & b \\ c & d \\ \end{vmatrix}', category: 'matrix', description: '2x2行列式' },
  ],
  integral: [
    { label: '积分', latex: '\\int', category: 'integral', description: '积分符号' },
    { label: '定积分', latex: '\\int_{a}^{b}', category: 'integral', description: '定积分' },
    { label: '双重积分', latex: '\\iint', category: 'integral', description: '双重积分' },
    { label: '三重积分', latex: '\\iiint', category: 'integral', description: '三重积分' },
    { label: '求和', latex: '\\sum', category: 'integral', description: '求和符号' },
    { label: '连乘', latex: '\\prod', category: 'integral', description: '连乘符号' },
  ],
  greek: [
    { label: 'α', latex: '\\alpha', category: 'greek', description: '希腊字母alpha' },
    { label: 'β', latex: '\\beta', category: 'greek', description: '希腊字母beta' },
    { label: 'γ', latex: '\\gamma', category: 'greek', description: '希腊字母gamma' },
    { label: 'δ', latex: '\\delta', category: 'greek', description: '希腊字母delta' },
    { label: 'ε', latex: '\\epsilon', category: 'greek', description: '希腊字母epsilon' },
    { label: 'ζ', latex: '\\zeta', category: 'greek', description: '希腊字母zeta' },
    { label: 'η', latex: '\\eta', category: 'greek', description: '希腊字母eta' },
    { label: 'θ', latex: '\\theta', category: 'greek', description: '希腊字母theta' },
    { label: 'π', latex: '\\pi', category: 'greek', description: '希腊字母pi' },
    { label: 'ω', latex: '\\omega', category: 'greek', description: '希腊字母omega' },
  ],
  chemistry: [
    { label: 'H₂O', latex: 'H_2O', category: 'chemistry', description: '水分子' },
    { label: 'CO₂', latex: 'CO_2', category: 'chemistry', description: '二氧化碳' },
    { label: '→', latex: '\\rightarrow', category: 'chemistry', description: '反应箭头' },
    { label: '⇌', latex: '\\rightleftharpoons', category: 'chemistry', description: '可逆反应' },
  ],
};

// 根据分类获取符号
export function getSymbolsByCategory(category: SymbolCategory): FormulaSymbol[] {
  return symbolLibrary[category] || [];
}

// 获取所有符号分类
export function getAllCategories(): SymbolCategory[] {
  return Object.keys(symbolLibrary) as SymbolCategory[];
}

// 分类显示名称映射
export const categoryDisplayNames: Record<SymbolCategory, string> = {
  basic: '基础运算',
  functions: '函数',
  matrix: '矩阵',
  integral: '积分与求和',
  greek: '希腊字母',
  chemistry: '化学符号',
};

// 在光标位置插入LaTeX代码
export function insertLatexAtCursor(text: string, latex: string, cursorPosition: number): { text: string; newCursorPosition: number } {
  const before = text.substring(0, cursorPosition);
  const after = text.substring(cursorPosition);
  
  // 如果LaTeX代码中包含{}，光标应放在{}之间
  if (latex.includes('{}')) {
    const newText = before + latex.replace('{}', '') + after;
    const newPosition = before.length + latex.indexOf('{}') + 1;
    return { text: newText, newCursorPosition: newPosition };
  }
  
  const newText = before + latex + after;
  return { text: newText, newCursorPosition: cursorPosition + latex.length };
}

// 简单验证LaTeX语法是否有效
export function validateLatex(latex: string): { valid: boolean; error?: string } {
  // 这里只是简单的括号匹配检查
  const stack: string[] = [];
  const brackets: { [key: string]: string } = {
    '(': ')',
    '[': ']',
    '{': '}'
  };
  
  for (let i = 0; i < latex.length; i++) {
    const char = latex[i];
    
    // 跳过转义的括号
    if (i > 0 && latex[i - 1] === '\\') continue;
    
    if (brackets[char]) {
      stack.push(char);
    } else if (Object.values(brackets).includes(char)) {
      const last = stack.pop();
      if (!last || brackets[last] !== char) {
        return { valid: false, error: `括号不匹配: 位置 ${i + 1}` };
      }
    }
  }
  
  if (stack.length > 0) {
    return { valid: false, error: `缺少右括号: ${stack.join(', ')}` };
  }
  
  return { valid: true };
}

// 格式化LaTeX代码（简单的美化）
export function formatLatex(latex: string): string {
  return latex
    .replace(/\\begin\{([^}]*)\}\s*/g, '\\begin{$1} ')
    .replace(/\s*\\end\{([^}]*)\}/g, ' \\end{$1}')
    .replace(/\s+/g, ' ') // 多个空格替换为单个空格
    .trim();
}